﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace WFL.Threading
{
    /// <summary>
    /// 读写锁（写优先）：共享读、读写互斥、写写互斥
    /// </summary>
    [Obsolete("微软官方类库已提供")]
    public class WriteReadObjectLock
    {
        private int _lock;
        private int _writeWaitCount;

        public WriteReadObjectLock()
        {
            _lock = 0;
            _writeWaitCount = 0;
        }

        public void AcquireRead()
        {
            lock (this)
            {
            Label_01:
                try
                {
                    while (_lock == -1
                        || _writeWaitCount != 0)
                    {
                        Monitor.Wait(this);
                        continue;
                    }
                }
                catch (ThreadInterruptedException)
                {
                    goto Label_01;
                }
                _lock++;
            }
        }

        public void AcquireWrite()
        {
            lock (this)
            {
                _writeWaitCount++;
            Label_01:
                try
                {
                    while (_lock != 0)
                    {
                        Monitor.Wait(this);
                        continue;
                    }
                }
                catch (ThreadInterruptedException)
                {
                    goto Label_01;
                }
                _lock = -1;
                _writeWaitCount--;
            }
        }

        public void ReleaseRead()
        {
            lock (this)
            {
                _lock--;
                if (_lock == 0)
                {
                    Monitor.PulseAll(this);
                }
            }
        }

        public void ReleaseWrite()
        {
            lock (this)
            {
                _lock = 0;
                Monitor.PulseAll(this);
            }
        }


    }
}
